package com.study.springCustom.spring.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BeanUtils {

    public static Object newInstance(Class clazzType) {
        try {
            // 默认获取的是无参构造（如果想通过有参构造的话，需要怎么做）
            // TODO <constructor-arg>
            Constructor<?> constructor = clazzType.getConstructor();
            // 通过构造器去创建实例
            Object bean = constructor.newInstance();
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void setProperty(Object bean, String name, Object valueToUse) throws Exception {
        Class<?> aClass = bean.getClass();
        Field field = aClass.getDeclaredField(name);
        field.setAccessible(true);
        field.set(bean, valueToUse);
    }

    public static void invokeMethod(Object bean, String methodName) {
        try {
            Class<?> clazzType = bean.getClass();
            Method method = clazzType.getMethod(methodName);
            method.invoke(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
